package com.sddongyun.common.utils;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.util.EntityUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lenovo
 * @date 2021-05-2416:46
 */
public class HttpClientUtil {

    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";
    // 设置连接超时时间，单位毫秒。
    private static int CONNECT_TIMEOUT = 130000;
    // 请求获取数据的超时时间(即响应时间)，单位毫秒。
    private static int SOCKET_TIMEOUT = 130000;
    // 设置从连接池中获取连接超时时间，单位毫秒。
    private static int CONNECT_REQUEST_TIMEOUT = 130000;

    /*设置请求头，伪装成浏览器请求header*/
    public static Map<String, String> headerMap;
    static {
        headerMap = new HashMap<String, String>();
        headerMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
        headerMap.put("Connection", "keep-alive");
        headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,image/webp,image/apng,*/*;q=0.8");
        headerMap.put("Accept-Language", "zh-CN,zh;q=0.8");
    }

    private static CloseableHttpClient httpClient = HttpClients.createDefault();

    public static CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public static void setHttpClient(CloseableHttpClient httpClient) {
        HttpClientUtil.httpClient = httpClient;
    }

    /**
     * 带参数的post请求
     */
    public static String doPost(String url, String reqJson, Map<String, String> headersMap)
            throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        //增加配置：各种超时等
        httpPost.setConfig(setRequestConfig());

        for(Map.Entry<String, String> entry : headersMap.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 判断map不为空
        if (reqJson != null) {
            byte []  bytes = reqJson.getBytes(ENCODING);
            InputStream is = new ByteArrayInputStream(bytes);
            InputStreamEntity ise = new InputStreamEntity(is);
            httpPost.setEntity(ise);
        }
        // 使用HttpClient发起请求，返回response
        CloseableHttpResponse response = httpClient.execute(httpPost);
        String rtn = EntityUtils.toString(response.getEntity(), ENCODING);

        // 返回结果
        return rtn;
    }

    /**
     * 设置 各种超时时间
     * 1. 设置连接超时时间
     * 2. 获取连接超时时间
     * 3. 获取数据的超时时间
     */
    public static RequestConfig setRequestConfig(){
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)
                .build();

        return requestConfig ;
    }

    public static void ybRequest(String [] s) throws UnsupportedEncodingException {

        Map headerMap = new HashMap();
        headerMap.put("content-type","text/html;charset=utf-8");
        String url = "http://10.34.17.208:8090/services/YtjServer";
        String rtn = "";
        String jsonParam = "<soapenv:Envelope xmlns:soapenv =\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd =\"http://www.ylzinfo.com/xsd\"><soapenv:Header/><soapenv:Body><xsd:ydjy_common_register><xsd:username>CDYTJ02</xsd:username><xsd:password >7f6d6b863be541677e464308fd7440dc</xsd:password ><xsd:machineid >zzj001</xsd:machineid ><xsd:xmlIn ><![CDATA[<soap:envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingstyle =\"http://schemas.xmlsoap.org/soap/encoding/\"><soap:header><in:system xmlns:in=\"http://www.ylzinfo.com/\"><para usr =\"CDYTJ02\"/><para pwd =\"7f6d6b863be541677e464308fd7440dc\"/><para machineid =\"zzj001\"/><para sid =\"ydjy_common_register\"/></in:system></soap:header><soap:body><in:business xmlns:in=\"http://www.ylzinfo.com/\"><para akb020=\"02\"/><para aac002=\"130824198510290010\"/><para aac003=\"曹宏博\"/><para ckc110=\"142\"/><para akc193=\"\"/><para aae005=\"\"/><para aae006=\"\"/><para akc194=\"\"/><para aae011=\"ytjzz\"/><para xae011=\"一体机自助\"/><para skc098=\"000\"/><paralist name=\"list01\"><row akc227=\"15\" ckc169=\"眼科门诊\" aae011=\"一体机自助\" cke086=\"\" cke089=\"1\" ska003=\"001\" ckc171=\"眼科门诊\" ckc170=\"普通号\" cke081=\"P\" aac001=\"130824198510290010\" akc220=\"2039||7519\" ckc158=\"1\" akc222=\"LS15011409\" akc223=\"普通号\" ckc197=\"15\" ckc198=\"1\" cke090=\"000\" ckc159='/' ckc160='/' ckc161=\"001102000010000-11020000100\" cke085=\"\" aka063=\"P\"></row></paralist></in:business></soap:body></soap:envelope>]]></xsd:xmlIn ></xsd:ydjy_common_register></soapenv:Body></soapenv:Envelope>";


        String method = "POST";
        String proxyRequestUri = "http://10.34.17.208:8090/services/YtjServer";

        ByteArrayInputStream sis = new ByteArrayInputStream(jsonParam.getBytes("UTF-8"));

        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        eProxyRequest.setEntity(new InputStreamEntity(sis, jsonParam.getBytes("UTF-8").length));

        eProxyRequest.setHeader("content-type","text/html;charset=utf-8");
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpHost httpHost= new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
            CloseableHttpResponse rtnResp =  HttpClientUtil.getHttpClient().execute(httpHost,eProxyRequest);
            rtn = EntityUtils.toString(rtnResp.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("filter中打印response： "+ rtn);

        System.out.println(rtn);
    }

    public static void main(String [] s) throws Exception {

        headerMap.put("content-type","text/html;charset=utf-8");
        String url = "http://localhost:8083/yb";
        String rtn = "";
        String jsonParam = "<soapenv:Envelope xmlns:soapenv =\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd =\"http://www.ylzinfo.com/xsd\"><soapenv:Header/><soapenv:Body><xsd:ydjy_common_register><xsd:username>CDYTJ02</xsd:username><xsd:password >7f6d6b863be541677e464308fd7440dc</xsd:password ><xsd:machineid >zzj001</xsd:machineid ><xsd:xmlIn ><![CDATA[<soap:envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingstyle =\"http://schemas.xmlsoap.org/soap/encoding/\"><soap:header><in:system xmlns:in=\"http://www.ylzinfo.com/\"><para usr =\"CDYTJ02\"/><para pwd =\"7f6d6b863be541677e464308fd7440dc\"/><para machineid =\"zzj001\"/><para sid =\"ydjy_common_register\"/></in:system></soap:header><soap:body><in:business xmlns:in=\"http://www.ylzinfo.com/\"><para akb020=\"02\"/><para aac002=\"130824198510290010\"/><para aac003=\"曹宏博\"/><para ckc110=\"142\"/><para akc193=\"\"/><para aae005=\"\"/><para aae006=\"\"/><para akc194=\"\"/><para aae011=\"ytjzz\"/><para xae011=\"一体机自助\"/><para skc098=\"000\"/><paralist name=\"list01\"><row akc227=\"15\" ckc169=\"眼科门诊\" aae011=\"一体机自助\" cke086=\"\" cke089=\"1\" ska003=\"001\" ckc171=\"眼科门诊\" ckc170=\"普通号\" cke081=\"P\" aac001=\"130824198510290010\" akc220=\"2039||7519\" ckc158=\"1\" akc222=\"LS15011409\" akc223=\"普通号\" ckc197=\"15\" ckc198=\"1\" cke090=\"000\" ckc159='/' ckc160='/' ckc161=\"001102000010000-11020000100\" cke085=\"\" aka063=\"P\"></row></paralist></in:business></soap:body></soap:envelope>]]></xsd:xmlIn ></xsd:ydjy_common_register></soapenv:Body></soapenv:Envelope>";
        rtn = HttpClientUtil.doPost(url,jsonParam,headerMap);

        System.out.println(rtn);
    }
}
